<template>
  <div ref="chart" style="width: 100%; height: 300px; background: #fff"></div>
</template>
<script setup>
  import { useStore } from 'vuex';
  import { ref, inject, onMounted } from 'vue';

  import * as echarts from 'echarts';

  let echartsInstance = null;
  const echartsOption = {
    grid: {
      left: '20px',
      right: '20px',
      bottom: '10px',
      top: '50px',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        animation: true
      },
      alwaysShowContent: false,
      formatter: function (params) {
        let index = 0;
        let result = `${params[0].name}<br />`;
        let dataIndex = params[0].dataIndex;

        groups.value.forEach((items, key) => {
          result += `<p class="chart-tooltip-line2"><b>${params[index].marker}${key} - ${items[dataIndex].ShareCode.substring(2)}</b> <b>${items[dataIndex].ProfitRevenue.toFixed(2)}元 / ${items[dataIndex].Quantity}股</b></p>`;
          result += `<p class="chart-tooltip-line2"><b>${params[1].marker}当日收益</b><b>${items[dataIndex].DailyRevenue}元</b></p>`;

          index++;
        });

        return result;
      }
    },
    legend: {
      show: false,
      selectedMode: false,
      data: []
    },
    xAxis: {
      type: 'category',
      axisLabel: {
        formatter: '{value}'
      },
      axisPointer: {
        show: true,
        label: {
          show: true,
          formatter: '{value}'
        }
      },
      data: []
    },
    yAxis: [
      {
        type: 'value',
        name: '收益(单位：元)',
        position: 'left',
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '每日收益(单位：元)',
        position: 'right',
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [],
    visualMap: {
      show: false,
      // 只对第二条线进行设置
      seriesIndex: 1,
      textStyle: {
        color: '#000'
      },
      pieces: [
        { min: 0, max: 2000000, label: '涨', color: '#C1232B' },
        { min: -20000, max: 0, label: '跌', color: 'green' }
      ],
      outOfRange: {
        color: 'green'
      }
    }
  };

  const props = defineProps({
    code: String
  });

  const $store = useStore();
  const $http = inject('$http');
  const $eventBus = inject('$eventBus');

  const chart = ref();
  const groups = ref(new Map());

  function renderIndexes() {
    $http.get(`/api/shares/daily/profit/${props.code}`, { hideTip: true }).then(res => {
      groups.value.clear();

      (res.datas || []).forEach(d => {
        let group = groups.value.get(d.ShareName) || [];

        group.push(d);
        groups.value.set(d.ShareName, group);
      });

      let keys = [];
      let series = [];

      groups.value.forEach((val, key) => {
        keys.push(key);
        keys.push(`${key} - 每日收益`);

        series.push({
          name: key,
          type: 'line',
          smooth: true,
          data: val.map(m => m.ProfitRevenue.toFixed(2)),
          markPoint: {
            data: [
              { type: 'max', name: '最大值' },
              { type: 'min', name: '最小值' }
            ]
          }
        });

        series.push({
          name: `${key} - 每日收益`,
          type: 'line',
          smooth: true,
          yAxisIndex: 1,
          data: (function () {
            let rs = [0];
            val[0].DailyRevenue = val[0].ProfitRevenue;

            for (let index = 1; index < val.length; index++) {
              let revenue = val[index].ProfitRevenue - val[index - 1].ProfitRevenue;

              rs.push(revenue);

              val[index].DailyRevenue = revenue;
            }

            return rs;
          })(),
          markPoint: {
            data: [
              { type: 'max', name: '最大值' },
              { type: 'min', name: '最小值' }
            ]
          },
          itemStyle: {
            color: function (params) {
              if (params.value > 0) {
                return '#C1232B';
              } else {
                return 'green';
              }
            }
          }
        });
      });

      echartsOption.series = series;
      echartsOption.legend.data = keys;
      echartsOption.xAxis.data = groups.value.get(keys[0]).map(r => r.AccountingDate);

      echartsInstance.setOption(echartsOption);
    });
  }

  function resizeChartPanel(area) {
    if (chart.value) {
      chart.value.style.width = area.width;
    }

    echartsInstance.resize();
  }

  onMounted(() => {
    echartsInstance = echarts.init(chart.value);

    resizeChartPanel($store.state.area.content);

    renderIndexes();

    $eventBus.on('windowResizeChanged', client => resizeChartPanel(client));
  });
</script>
<style lang="less" scoped>
  :deep(.chart-tooltip-line2) {
    padding: 0;
    margin: 5px 0 0 0;
    min-width: 200px;

    > b {
      width: 100%;
      display: block;
      text-indent: 15px;

      &:first-of-type {
        text-indent: 0;
      }
    }
  }
</style>
